//
//  ZCameraViewController.m
//  danpin
//
//  Created by chuangjia on 5/8/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "ZCameraViewController.h"
#import "ZCameraPhotoEdit.h"
#import "ZCameraSlideView.h"
#import "ZCameraSlideUpView.h"
#import "ZCameraSlideDownView.h"

@interface ZCameraViewController ()

@property (strong, nonatomic) UIView *captureView;
@property (strong, nonatomic) UIView *bottomView;

@property (strong, nonatomic) UIButton *flashButton;
@property (strong, nonatomic) UIButton *shotButton;
@property (strong, nonatomic) ZCameraSlideView *slideUpView;
@property (strong, nonatomic) ZCameraSlideView *slideDownView;

@property (strong, nonatomic) ZCamera *camera;
@property (nonatomic) CGFloat beginPinchGestureScale;
@property (nonatomic) CGFloat effectiveScale;
@property (nonatomic) BOOL wasLoaded;

- (IBAction)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer;
- (IBAction)handleTapGesture:(UITapGestureRecognizer *)recognizer;

- (void)zoomWithRecognizer:(UIPinchGestureRecognizer *)recognizer;

@end



@implementation ZCameraViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=CameraRGB(0x1e1e1e);

    if (!_camera){
        _camera = [ZCamera cameraWithFlashButton:_flashButton];
    }
    _effectiveScale = 1.;

    [self.view addSubview:self.captureView];
    [self.view addSubview:self.bottomView];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];

    _flashButton.enabled = NO;
    _shotButton.enabled = NO;
    [_camera startRunning];
    [ZCameraSlideView hideSlideUpView:self.slideUpView slideDownView:self.slideDownView atView:self.captureView completion:^{
        _flashButton.enabled = YES;
        _shotButton.enabled = YES;
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (_wasLoaded == NO) {
        _wasLoaded = YES;
        [_camera insertSublayerWithCaptureView:self.captureView atRootView:self.view];
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [_camera stopRunning];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
      NSLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)dealloc{
    self.captureView=nil;
    self.bottomView=nil;
    self.slideDownView=nil;
    self.slideUpView=nil;
    [self.camera stopRunning];
    self.camera=nil;
   
    NSLog(@"%s", __PRETTY_FUNCTION__);
}
- (BOOL)prefersStatusBarHidden
{
    return YES;
}

#pragma mark -
#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]]) {
        _beginPinchGestureScale = _effectiveScale;
    }
    
    return YES;
}


- (IBAction)flashTapped
{
    [_camera changeFlashModeWithButton:_flashButton];
}

- (IBAction)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer
{
    [self zoomWithRecognizer:recognizer];
}

- (IBAction)handleTapGesture:(UITapGestureRecognizer *)recognizer
{
    CGPoint touchPoint = [recognizer locationInView:self.captureView];
    [_camera focusView:self.captureView inTouchPoint:touchPoint];
    
}

#pragma mark -
#pragma mark - Private methods


- (void)zoomWithRecognizer:(UIPinchGestureRecognizer *)recognizer
{
    BOOL allTouchesAreOnThePreviewLayer = YES;
    NSInteger numberOfTouches = [recognizer numberOfTouches];
    
    AVCaptureVideoPreviewLayer *previewLayer = [_camera previewLayer];
    
    for (NSInteger i = 0; i < numberOfTouches; i++) {
        CGPoint location = [recognizer locationOfTouch:i inView:_captureView];
        CGPoint convertedLocation = [previewLayer convertPoint:location fromLayer:previewLayer.superlayer];
        
        if ([previewLayer containsPoint:convertedLocation] == NO) {
            allTouchesAreOnThePreviewLayer = NO;
            break;
        }
    }
    
    if (allTouchesAreOnThePreviewLayer) {
        _effectiveScale = _beginPinchGestureScale * [recognizer scale];
        
        if (_effectiveScale < 1.) {
            _effectiveScale = 1.;
        }
        
        AVCaptureStillImageOutput *stillImageOutput = [_camera stillImageOutput];
        CGFloat maxScaleAndCropFactor = [[stillImageOutput connectionWithMediaType:AVMediaTypeVideo] videoMaxScaleAndCropFactor];
        
        if (_effectiveScale > maxScaleAndCropFactor) {
            _effectiveScale = maxScaleAndCropFactor;
        }
        
        [CATransaction begin];
        [CATransaction setAnimationDuration:.025];
        [previewLayer setAffineTransform:CGAffineTransformMakeScale(_effectiveScale, _effectiveScale)];
        [CATransaction commit];
    }
}
//
-(UIView*)captureView
{
    if (!_captureView) {
        UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(zoomWithRecognizer:)];
        [pinchRecognizer setDelegate:self];
        UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTapGesture:)];
        self.captureView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,  self.view.frame.size.width)];
        self.captureView.backgroundColor = [UIColor clearColor];
        self.captureView.userInteractionEnabled =YES;
        [self.captureView addGestureRecognizer:tapGesture];
        [self.captureView addGestureRecognizer:pinchRecognizer];
        tapGesture=nil;
        pinchRecognizer=nil;
    }
    return _captureView;
}
-(UIView *)slideUpView
{
    if (!_slideUpView) {
        self.slideUpView =[[ZCameraSlideUpView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,  self.view.frame.size.width)];
        self.slideUpView.backgroundColor = CameraRGB(0x1e1e1e);
    }
    return _slideUpView;
}
-(UIView *)slideDownView
{
    if (!_slideDownView) {
        self.slideDownView =[[ZCameraSlideDownView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,  self.view.frame.size.width)];
        self.slideDownView.backgroundColor = CameraRGB(0x1e1e1e);
    }
    return _slideDownView;
}
-(UIView*)bottomView
{
    if (!_bottomView) {
        self.bottomView =[[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.width, self.view.frame.size.width, self.view.frame.size.height - self.view.frame.size.width)];
        self.bottomView.backgroundColor = CameraRGB(0x1e1e1e);
        //
        _shotButton = [[UIButton alloc] initWithFrame:CGRectMake((self.bottomView.frame.size.width -80)/2, (self.bottomView.frame.size.height -130)/2, 80,80)];
        _shotButton.tag=9;
        [_shotButton setImage:[UIImage imageNamed:@"shot.png"] forState:UIControlStateNormal];
        [_shotButton addTarget:self action:@selector(toolButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:_shotButton];
        
        //底部工具兰
        UIView *toolBarView =[[UIView alloc] initWithFrame:CGRectMake(0,  self.bottomView.frame.size.height-50, self.bottomView.frame.size.width,50)];
        toolBarView.backgroundColor=CameraRGB(0x1e1e1e);
        //
        UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        backBtn.tag=10;
        UIImage *backImage = [UIImage imageNamed:@"back1.png"];
        [backBtn setImage: backImage forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(toolButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [backBtn setFrame:CGRectMake(0, 0, 50, 50)];
        [toolBarView addSubview:backBtn];
        //
        
        _flashButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _flashButton.tag =11;
        [_flashButton setBackgroundImage:[UIImage imageNamed:@"shanguangdeng.png"] forState:UIControlStateNormal];
        [_flashButton addTarget:self action:@selector(toolButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [_flashButton setFrame:CGRectMake(self.bottomView.frame.size.width-150, 0, 50, 50)];
        [toolBarView addSubview:_flashButton];
        
        //
        UIButton *grid = [UIButton buttonWithType:UIButtonTypeCustom];
        grid.tag =12;
        [grid setBackgroundImage:[UIImage imageNamed:@"grid.png"] forState:UIControlStateNormal];
        [grid addTarget:self action:@selector(toolButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [grid setFrame:CGRectMake(self.bottomView.frame.size.width-100, 0, 50, 50)];
        [toolBarView addSubview:grid];
        
        //
        UIButton *deviceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        deviceBtn.tag =13;
        [deviceBtn setBackgroundImage: [UIImage imageNamed:@"fanzhuan.png"] forState:UIControlStateNormal];
        [deviceBtn addTarget:self action:@selector(toolButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [deviceBtn setFrame:CGRectMake(self.bottomView.frame.size.width-50, 0,50, 50)];
        [toolBarView addSubview:deviceBtn];
        [self.bottomView addSubview:toolBarView];
    }
    return _bottomView;
}
-(void)toolButtonPressed:(id)sender
{
    UIButton *btn =(UIButton *)sender;
    switch (btn.tag) {
        case 9:
        {
            _shotButton.enabled = NO;
            [ZCameraSlideView showSlideUpView:self.slideUpView slideDownView:self.slideDownView atView:self.captureView completion:^{
                [_camera takePhotoWithCaptureView:self.captureView effectiveScale:_effectiveScale videoOrientation:AVCaptureVideoOrientationPortrait completion:^(UIImage *photo) {
                    
                    ZCameraPhotoEdit *viewController = [ZCameraPhotoEdit newWithDelegate:_delegate photo:photo type:0];
                    [self.navigationController pushViewController:viewController animated:YES];
                   _shotButton.enabled = YES;
                }];
            }];
        }
            break;
        case 10:
        {
            if (self.navigationController) {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
        case 11:
        {
            if (_camera) {
                 [_camera changeFlashModeWithButton:_flashButton];
            }
        }
            break;
        case 12:
        {
            if (_camera) {
                 [_camera disPlayGridView];
            }
         
        }
            break;
        case 13:
        {
            if (_camera) {
                 [_camera toogleWithFlashButton:_flashButton];
            }
        }
            break;
            
        default:
            break;
    }
}
@end
